package com.lcredu.filter;

import com.lcredu.entity.Member;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author 黎长容
 * @date 2025-07-10 11:01
 */
public class CartFilter implements Filter {
    private List<String> excludedUrls;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //获取配置的放行url
        String initParameter = filterConfig.getInitParameter("excludedUrls");

        String[] split = initParameter.split(",");

        //数组转集合
        excludedUrls = Arrays.asList(split);

        System.out.println("CartFilter创建了...");
    }

    /**
     * 黎长容知识12. 过滤器的配置
     * 1.创建过滤器类实现Filter接口
     * 2.配置web.xml
     * 3.业务鉴权,符合规范就放心,不符合就直接返回登录页面
     * 4.转发不走过滤器
     * .request.getServletPath() = /views/cart/cart.jsp
     * .request.getRequestURL() = //localhost:8080/jiaju_mall/views/cart/cart.jsp
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String servletPath = request.getServletPath();

        if (!excludedUrls.contains(servletPath)) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if ("adminId".equals(cookie.getName())){
                        filterChain.doFilter(servletRequest, servletResponse);
                    }
                }
            }
            //没有包含走过滤器
            Member user = (Member) request.getSession().getAttribute("user");
            if (user != null ) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            } else {
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                request.getRequestDispatcher("/views/member/login.jsp").forward(request, response);
            }
        }

        //否则直接放行
        filterChain.doFilter(servletRequest, servletResponse);


    }

    @Override
    public void destroy() {
        System.out.println("CartFilter销毁了...");
    }
}
